<template>
  <div class="app-container">
    <vxe-grid
      v-bind="gridOptions"
      align="center"
      :data="bloods"
      :loading="loading"
    >
      <template #form>
        <search :search-fields="searchFields" @queryData="queryData" />
        <el-table :data="census" style="width: 100%">
          <el-table-column
            align="center"
            class-name="font-bold"
            label="全部"
            prop="date"
          >
            <el-table-column align="center" label="血袋" prop="date">
              <template #default="{ row }">
                <b class="font18">{{ row.ALL.count }}</b>
              </template>
            </el-table-column>
            <el-table-column align="center" label="血量" prop="date">
              <template #default="{ row }">
                <b class="font18">{{ row.ALL.capacity }}</b>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column
            align="center"
            class-name="bg-primary-plain"
            label="A"
            prop="date"
          >
            <el-table-column
              align="center"
              class-name="bg-primary-plain"
              label="血袋"
              prop="date"
            >
              <template #default="{ row }">
                <b class="font18">{{ (row.A && row.A.count) || 0 }}</b>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              class-name="bg-primary-plain"
              label="血量"
              prop="date"
            >
              <template #default="{ row }">
                <b class="font18">{{ (row.A && row.A.capacity) || 0 }}</b>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column
            align="center"
            class-name="bg-warning-plain"
            label="B"
            prop="name"
          >
            <el-table-column
              align="center"
              class-name="bg-warning-plain"
              label="血袋"
              prop="date"
            >
              <template #default="{ row }">
                <b class="font18">{{ (row.B && row.B.count) || 0 }}</b>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              class-name="bg-warning-plain"
              label="血量"
              prop="date"
            >
              <template #default="{ row }">
                <b class="font18">{{ (row.B && row.B.capacity) || 0 }}</b>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column
            align="center"
            class-name="bg-success-plain"
            label="AB"
            prop="address"
          >
            <el-table-column
              align="center"
              class-name="bg-success-plain"
              label="血袋"
              prop="date"
            >
              <template #default="{ row }">
                <b class="font18">{{ (row.AB && row.AB.count) || 0 }}</b>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              class-name="bg-success-plain"
              label="血量"
              prop="date"
            >
              <template #default="{ row }">
                <b class="font18">{{ (row.AB && row.AB.capacity) || 0 }}</b>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column
            align="center"
            class-name="bg-danger-plain"
            label="O"
            prop="address"
          >
            <el-table-column
              align="center"
              class-name="bg-danger-plain"
              label="血袋"
              prop="date"
            >
              <template #default="{ row }">
                <b class="font18">{{ (row.O && row.O.count) || 0 }}</b>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              class-name="bg-danger-plain"
              label="血量"
              prop="date"
            >
              <template #default="{ row }">
                <b class="font18">{{ (row.O && row.O.capacity) || 0 }}</b>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </template>
      <template #toolbar_buttons>
        <el-button
          icon="el-icon-edit"
          size="mini"
          type="primary"
          @click="handleEdit"
        >
          修改
        </el-button>
        <el-button
          icon="el-icon-c-scale-to-original"
          size="mini"
          type="success"
          @click="handlePre"
        >
          制备
        </el-button>
        <el-button
          icon="el-icon-copy-document"
          size="mini"
          type="danger"
          @click="handleSub"
        >
          分装
        </el-button>
        <el-button
          icon="el-icon-printer"
          size="mini"
          type="warning"
          @click="handleMultiPrint"
        >
          批量打印
        </el-button>
        <el-dropdown
          style="margin-right: 12px; margin-left: auto"
          @command="handleCollect"
        >
          <el-button :loading="requestLoading" size="mini" type="primary">
            血液接收
            <i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :command="0">差量接收</el-dropdown-item>
            <el-dropdown-item :command="1">全量接收</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <!-- <el-button
          icon="el-icon-plus"
          :loading="requestLoading"
          size="mini"
          style="margin-right: 12px; margin-left: auto"
          type="primary"
          @click="handleCollect"
        >
          血液接收
        </el-button> -->
      </template>
      <template #id="{ row }">
        <el-tag v-if="row.subFrom" type="primary">分装</el-tag>
        <el-tag v-if="row.preFrom" type="success">制备</el-tag>
        <span class="ml4" :class="row.status < 0 ? 'color-danger' : ''">
          {{ row.id }}
        </span>
      </template>
      <template #syncable="{ row }">
        <i v-if="row.syncable" class="el-icon-check color-success font24"></i>
        <i v-else class="el-icon-close color-danger font24"></i>
      </template>
      <template #printable="{ row }">
        <i v-if="row.printable" class="el-icon-check color-success font24"></i>
        <i v-else class="el-icon-close color-danger font24"></i>
      </template>
      <template #capacity="{ row }">
        {{ (+row.capacity).toFixed(1) }}
      </template>
      <template #source="{ row }">
        {{ getBloodFrom(row) }}
      </template>
      <template #status="{ row }">
        <el-tag :type="getStatus(row.status, 'type')">
          {{ getStatus(row.status) }}
        </el-tag>
      </template>
      <template #bloodUser="{ row }">
        {{ getBloodUser(row) }}
      </template>
      <template #preTime="{ row }">
        {{ getPreTime(row) }}
      </template>
      <template #operate="{ row }">
        <el-link
          class="mr12"
          :disabled="+row.status !== 0"
          icon="el-icon-edit"
          type="primary"
          @click="handleEdit(row)"
        >
          修改
        </el-link>
        <el-link
          class="mr12"
          :disabled="+row.status !== 0 || row.syncable === 0"
          icon="el-icon-c-scale-to-original"
          type="success"
          @click="handlePre(row)"
        >
          制备
        </el-link>
        <el-link
          class="mr12"
          :disabled="+row.status !== 0 || row.syncable === 0"
          icon="el-icon-copy-document"
          type="danger"
          @click="handleSub(row)"
        >
          分装
        </el-link>
        <el-link
          :disabled="+row.status !== 0"
          icon="el-icon-printer"
          type="warning"
          @click="handlePrint([row])"
        >
          打印
        </el-link>
      </template>
      <template #pager>
        <vxe-pager
          :current-page.sync="current_page"
          :layouts="[
            'Sizes',
            'PrevJump',
            'PrevPage',
            'Number',
            'NextPage',
            'NextJump',
            'FullJump',
            'Total',
          ]"
          :page-size.sync="per_page"
          :perfect="true"
          :total="total"
          @page-change="handlePageChange"
        />
      </template>
    </vxe-grid>
    <buy ref="buy" @submit="multiSave" />
    <prepare ref="pre" @submit="doPre" />
    <subpackage ref="sub" @submit="doSub" />
    <edit ref="edit" @submit="doEdit" />
    <collect ref="collect" @submit="doCollect" />
    <print ref="print" name="blood" @getAll="getAll" />
    <multi-print ref="multiPrint" />
  </div>
</template>

<script>
  import {
    getAll,
    getCensus,
    multiSave,
    updateOne as doEdit,
    doSub,
    doPre,
    doFetch,
  } from '@/api/blood'
  import { getAll as getBloodSources } from '@/api/bloodSource'
  import Buy from './components/Buy'
  import Prepare from './components/Pre'
  import Subpackage from './components/Sub'
  import Edit from './components/Edit'
  import Collect from './components/Collect'
  import Print from '@/components/Print'
  import MultiPrint from './components/MultiPrint'
  import Search from '@/components/Search'
  import { removeEmptyField } from '@/utils'
  import { mapGetters } from 'vuex'
  export default {
    components: {
      Buy,
      Prepare,
      Subpackage,
      Edit,
      Collect,
      Search,
      Print,
      MultiPrint,
    },
    data() {
      return {
        requestLoading: false,
        bloodGroups: ['A', 'B', 'AB', 'O'],
        bloodRhds: ['阳性', '阴性'],
        searchFields: [],
        bloods: [],
        census: [],
        total: 0,
        current_page: 1,
        per_page: 10,
        loading: true,
        params: {
          page: 1,
          pagesize: 10,
        },
        gridOptions: {
          ref: 'table',
          border: true,
          height: 'auto',
          resizable: true,
          size: 'small',
          stripe: true,
          keepSource: true,
          printConfig: {},
          importConfig: {},
          exportConfig: {},
          rowClassName: ({ row }) => {
            if (row.printable) {
              return 'bg-primary-plain'
            }
          },
          editConfig: {
            trigger: 'click',
            mode: 'row',
            showStatus: true,
          },
          toolbarConfig: {
            size: 'small',
            slots: {
              buttons: 'toolbar_buttons',
            },
            perfect: true,
            print: {
              icon: 'vxe-icon-print',
            },
            custom: true,
          },
          columns: [
            { type: 'checkbox', width: 40 },
            {
              title: '#',
              field: 'idx',
              type: 'seq',
              width: 40,
            },
            {
              title: '同步',
              field: 'syncable',
              showOverflow: true,
              slots: { default: 'syncable' },
              width: 50,
            },
            {
              title: '打印',
              field: 'printable',
              showOverflow: true,
              slots: { default: 'printable' },
              width: 50,
            },
            {
              title: '血型',
              field: 'abo',
              showOverflow: true,
              sortable: true,
              width: 70,
            },
            {
              title: 'Rh(D)',
              field: 'rhd',
              showOverflow: true,
              sortable: true,
              width: 75,
            },
            {
              title: '血液成分',
              field: 'product.name',
              showOverflow: true,
              sortable: true,
              width: 150,
            },
            {
              title: '血量(U)',
              field: 'capacity',
              showOverflow: true,
              slots: { default: 'capacity' },
              sortable: true,
              width: 85,
            },
            {
              title: '血袋号',
              align: 'left',
              field: 'id',
              showOverflow: true,
              sortable: true,
              slots: { default: 'id' },
              width: 150,
            },
            {
              title: '配血管号',
              field: 'tube_number',
              showOverflow: true,
              sortable: true,
              width: 95,
            },
            {
              title: '血源',
              field: 'source',
              showOverflow: true,
              sortable: true,
              slots: { default: 'source' },
              width: 130,
            },
            {
              title: '原始血袋号',
              field: 'id_out',
              showOverflow: true,
              sortable: true,
              width: 145,
            },
            {
              title: '捐血者',
              field: 'blood_user',
              showOverflow: true,
              width: 80,
              slots: { default: 'bloodUser' },
            },
            {
              title: '血员号',
              field: 'donor_id',
              showOverflow: true,
              width: 80,
            },
            {
              title: '采血时间',
              field: 'collect_time_date',
              showOverflow: true,
              sortable: true,
              width: 125,
            },
            {
              title: '失效时间',
              field: 'invalid_time_date',
              showOverflow: true,
              sortable: true,
              width: 125,
            },
            {
              title: '制备时间',
              field: 'preFrom.created_at',
              showOverflow: true,
              sortable: true,
              slots: { default: 'preTime' },
              width: 125,
            },
            {
              title: '状态',
              field: 'status',
              fixed: 'right',
              showOverflow: true,
              sortable: true,
              slots: { default: 'status' },
              width: 95,
            },
            {
              title: '入库者',
              field: 'created_user',
              showOverflow: true,
              sortable: true,
              width: 85,
            },
            {
              title: '入库时间',
              field: 'created_at_date',
              showOverflow: true,
              sortable: true,
              width: 125,
            },
            {
              title: '申请单号',
              field: 'apply_num',
              showOverflow: true,
              sortable: true,
              width: 95,
            },
            {
              title: '操作',
              field: 'act',
              width: 280,
              fixed: 'right',
              slots: { default: 'operate' },
            },
          ],
        },
      }
    },
    computed: {
      ...mapGetters(['products']),
    },
    created() {
      this.getSearchFields()
      this.getAll()
      this.getCensus()
      this.getBloodSources()
    },
    methods: {
      getBloodSources() {
        getBloodSources({ pagesize: 100 }).then((res) => {
          this.bloodSources = res.data.data
          this.getSearchFields()
        })
      },
      getBloodUser(blood) {
        if (blood.blood_user) {
          return blood.blood_user
        }
        if (blood.id_out) {
          return blood.id_out.replace('=', '').substr(5, 8)
        }
        return ''
      },
      getBloodFrom(row) {
        if (row.from) {
          return (row.fromAttr && row.fromAttr.name) || row.from || ''
        }
        return ''
      },
      getSearchFields() {
        this.searchFields = [
          {
            name: 'id',
            placeholder: '血袋号',
            component: 'input',
            className: 'wd150',
          },
          {
            name: 'tube_number',
            placeholder: '配血试管号',
            component: 'input',
            className: 'wd150',
          },
          {
            name: 'id_out',
            placeholder: '原始血袋号',
            component: 'input',
            className: 'wd150',
          },
          {
            name: 'product_id_path',
            placeholder: '血液成分',
            component: 'cascader',
            className: 'wd200',
            options: this.products,
            props: { value: 'id', label: 'name' },
          },
          {
            name: 'abo',
            placeholder: '血型',
            component: 'select',
            className: 'wd150',
            options: this.bloodGroups,
            props: {},
          },
          {
            name: 'rhd',
            placeholder: 'Rh(D)',
            component: 'select',
            className: 'wd150',
            options: this.bloodRhds,
            props: {},
          },
          {
            name: 'from',
            placeholder: '血源',
            component: 'select',
            className: 'wd200',
            options: this.bloodSources,
            props: { value: 'id', label: 'name' },
          },
          {
            name: 'collect_time',
            placeholder: '采血时间',
            component: 'datepicker',
            className: 'wd200',
          },
          {
            name: 'invalid_time',
            placeholder: '失效时间',
            component: 'datepicker',
            className: 'wd200',
          },
          {
            name: 'pre_time',
            placeholder: ['制备开始时间', '结束时间'],
            component: 'daterange',
            className: 'wd300',
          },
          {
            name: 'created_at',
            placeholder: ['入库开始时间', '结束时间'],
            component: 'datetimerange',
            className: 'wd300',
          },
          {
            name: 'created_user',
            placeholder: '入库者',
            component: 'input',
            className: 'wd150',
          },
          {
            name: 'apply_num',
            placeholder: '申请单号',
            component: 'input',
            className: 'wd150',
          },
        ]
      },
      handleEdit(row) {
        this.$refs.edit.show(row)
      },
      handlePre(row) {
        this.$refs.pre.show(row)
      },
      handleSub(row) {
        this.$refs.sub.show(row)
      },
      handleBuy() {
        this.$refs.buy.show()
      },
      handleCollect(command) {
        if (+command === 1) {
          this.$baseConfirm(
            `确定要全量拉取选记录吗？该操作会覆盖已经在库并已经修改过的记录`,
            '操作确认',
            async () => {
              this.doFetch(command)
            }
          )
        } else {
          this.doFetch(command)
        }
      },
      async doFetch(force) {
        doFetch({ force })
          .then((res) => {
            // const data = res.data
            // if (data.length > 0) {
            //   console.log(data)
            //   this.$refs.print.show(
            //     data.map((val) => {
            //       return { id: val }
            //     })
            //   )
            // }
            this.$baseMessage(res.msg, 'success', 'vab-hey-message-success')
            setTimeout(() => {
              this.getAll()
            }, 50)
          })
          .catch(() => {})
      },
      handlePrint(row) {
        this.$refs.print.show(row)
      },
      handleMultiPrint() {
        let selectRecords = this.$refs.table.getCheckboxRecords()
        if (selectRecords.length === 0) {
          this.$baseMessage(
            '请至少选择一条记录',
            'error',
            'vab-hey-message-error'
          )
          return
        }
        this.$refs.print.show(selectRecords)
      },
      handleCommand(command) {
        if (command === 'buy') {
          this.handleBuy()
        } else {
          this.handleCollect()
        }
      },
      async doPre(blood_id, postData) {
        doPre(blood_id, postData)
          .then((res) => {
            const {
              data: { result, exceptions },
              msg,
            } = res
            this.$refs.print.show(result)
            setTimeout(() => {
              if (exceptions.length > 0) {
                this.$baseAlert(exceptions.join('<br/>'), '操作提醒', () => {
                  this.$refs.pre.close()
                  this.getAll()
                })
              } else {
                this.$baseMessage(msg, 'success', 'vab-hey-message-success')
                this.$refs.pre.close()
                this.getAll()
              }
            }, 1000)
          })
          .catch(() => {
            this.$refs.pre.hideLoading()
          })
      },
      async doSub(blood_id, postData) {
        const { data, msg } = await doSub(blood_id, postData)
        this.$refs.print.show(data)
        setTimeout(() => {
          this.$baseMessage(msg, 'success', 'vab-hey-message-success')
          this.$refs.sub.close()
          this.getAll()
        }, 1000)
      },
      async doEdit(blood_id, postData) {
        const { msg } = await doEdit(blood_id, postData)
        this.$baseMessage(msg, 'success', 'vab-hey-message-success')
        this.$refs.edit.close()
        this.getAll()
      },
      async doCollect(form) {
        console.log(form)
        this.$baseMessage('此功能待模拟', 'error', 'vab-hey-message-error')
      },
      async multiSave(datas) {
        const { msg } = await multiSave(datas)
        this.$baseMessage(msg, 'success', 'vab-hey-message-success')
        this.$refs.buy.close()
        this.getAll()
      },
      queryData(queryForm) {
        this.params = { page: 1, ...queryForm }
        this.getAll()
        this.getCensus()
      },
      async getAll() {
        const {
          data: { data, total, per_page, current_page },
        } = await getAll(removeEmptyField(this.params))
        this.bloods = data
        this.total = total
        this.per_page = per_page
        this.current_page = current_page
        this.loading = false
      },
      async getCensus() {
        const { data } = await getCensus(removeEmptyField(this.params))
        this.census = data
      },
      handlePageChange({ currentPage, pageSize }) {
        this.params.page = currentPage
        this.params.pagesize = pageSize
        this.getAll()
      },
      getStatus(status, attr = 'name') {
        const statusMap = {
          0: { type: 'success', name: '闲置' },
          '-2': { type: 'danger', name: '出库-制备' },
          '-1': { type: 'danger', name: '出库-分装' },
          '-3': { type: 'danger', name: '出库-报废' },
        }
        return statusMap[status][attr]
      },
      getPreTime(row) {
        if (row.preFrom) {
          return row.preFrom.created_at || ''
        }
        if (row.subFrom) {
          return row.subFrom.created_at || ''
        }
        return ''
      },
    },
  }
</script>

<style lang="scss" scoped></style>
